package rwlivbk.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.io.IOException;
import java.net.MalformedURLException;

@CrossOrigin
@RestController
@RequestMapping("/admin-api")
public class ImageController {



    @PostMapping("/upload-dish-image")
    public ResponseEntity<?> uploadImage(@RequestParam("file") MultipartFile file) {
        try {

            Path imageDirectory = Paths.get("./images/dishes").toAbsolutePath().normalize();

            // 检查目录是否存在，如果不存在则创建
            Files.createDirectories(imageDirectory);

            // 获取原始文件名
            String fileName = file.getOriginalFilename();

            // 生成文件的保存路径
            Path targetLocation = imageDirectory.resolve(fileName);

            // 将文件复制到目标位置（替换现有文件）
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            // 构建并返回文件的下载URL
            String fileDownloadUri = "/admin-api/images/dishes/" + fileName;

            return ResponseEntity.ok(fileDownloadUri);
        } catch (IOException ex) {
            return ResponseEntity.internalServerError().body("Could not store file " + file.getOriginalFilename() + ". Please try again!");
        }
    }


    private final Path baseDirectory = Paths.get("./").toAbsolutePath().normalize();

    @GetMapping("/images/**/{filename:.+}")
    public ResponseEntity<Resource> getImage(@PathVariable String filename, HttpServletRequest request) throws MalformedURLException {
        // 获取完整的请求URI

        Path imageDirectory = Paths.get("./images").toAbsolutePath().normalize();

        String requestUri = request.getRequestURI();

        // 从请求URI中提取文件路径
        String filePath = extractFilePath(requestUri);

        Path imagePath = imageDirectory.resolve(filePath).normalize().toAbsolutePath();

        // 后续逻辑保持不变...

        // 转换为相对于基准目录的路径
        Path relativeImagePath = baseDirectory.relativize(imagePath);

        // 现在比较两个相对路径
        if (!relativeImagePath.startsWith(imageDirectory.getFileName())) {
            throw new MalformedURLException("Image path is invalid.");
        }

        // 防止路径遍历攻击
        if (!imagePath.startsWith(imageDirectory)) {
            throw new MalformedURLException("Image path is invalid.");
        }

        UrlResource image = new UrlResource(imagePath.toUri());

        // 确保文件可读
        if (!image.isReadable()) {
            throw new MalformedURLException("Could not read file: " + filePath);
        }

        // 根据文件扩展名确定媒体类型
        String contentType = determineContentType(filePath);
        MediaType mediaType = MediaType.parseMediaType(contentType);

        return ResponseEntity.ok()
                .contentType(mediaType)
                .body(image);
    }

    private String extractFilePath(String requestUri) {
        // 假设请求URI的形式是 "/admin-api/images/some/path/filename.jpg"
        // 我们需要提取 "some/path/filename.jpg" 部分
        return requestUri.substring(requestUri.indexOf("/images/") + 8);
    }

    private String determineContentType(String filename) {
        String extension = filename.toLowerCase().substring(filename.lastIndexOf(".") + 1);
        switch (extension) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            default:
                return "application/octet-stream"; // 通用文件类型
        }
    }
}
